﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Xml;
using System.IO;
using System.Net;
using HtmlExtractor;


namespace Reader.Domain
{
    public partial class BookContent
    {
       
        public string BookPage
        {
            get;
            set;
        }

        public string BookName
        {
            get;
            set;
        }

        public string Author
        {
            get;
            set;
        }
        private List<UriName> chapters = new List<UriName>();
        public List<UriName> Chapters
        {
            get;
            set;
        }
        private List<UriName> vipChapters = new List<UriName>();
        public List<UriName> VipChapters
        {
            get;
            set;
        }
    }
    public partial class BookContent
    {
        private static void SaveXmlFile(BookContent bookContent, string uri)
        {
            XmlWriterSettings ws = new XmlWriterSettings();
            ws.Indent = true;
            DataContractSerializer serializer = new DataContractSerializer(bookContent.GetType());
            try
            {

                string fileLoc = ReaderPath.GetSiteFileName(uri);
                if (!File.Exists(fileLoc))
                {
                    using (XmlWriter writer = XmlWriter.Create(File.Create(fileLoc), ws))
                    {
                        serializer.WriteObject(writer, bookContent);
                       
                    }
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void SaveXmlFile(string uri,Action<BookContent> saveChapter)
        {
            BookContent obj;
            if (Cache.Current.TryGet(uri, out obj))
            {
                SaveXmlFile(obj, uri);
                saveChapter(obj);
            }
            else
            {
                WebClient client = new WebClient();
                client.Encoding = new Gb2312Encoding();
                client.DownloadStringAsync(new Uri(uri));
                client.DownloadStringCompleted += (s, args) =>
                {
                    if (args.Error == null)
                    {
                        obj = SaveFile.GenerateObject<BookContent>(args.Result, uri);                        
                        Cache.Current.Add(uri, obj);
                        SaveXmlFile(obj, uri);
                        saveChapter(obj);
                    }
                };

            }
        }
    }

}
